<template>
  <div class="dashboard">
    <!-- 头部标题 -->
    <el-card class="header-card">
      <div class="header">
        <h2>北仑区传媒中心项目管理系统</h2>
        <el-tag size="medium">欢迎 {{ name }}</el-tag>
      </div>
    </el-card>

    <el-row :gutter="10" type="flex">
      <!-- 待办事项列表 -->
      <el-col :span="10">
        <el-card class="todo-section">
          <div slot="header" class="todo-header">
            <el-badge :value="count" :max="99" class="todo-badge" type="danger">
              <el-button size="small">待办事项</el-button>
            </el-badge>
          </div>

          <el-table :data="todoItems" style="width: 100%">
            <el-table-column type="index" width="50" />
            <el-table-column prop="content">
              <template slot-scope="scope">
                <span @click="handleTodoClick(scope.row)">{{
                  scope.row.content
                }}</span>
                <el-tag
                  v-if="!admin"
                  size="medium"
                  :type="scope.row.isSel === 0 ? 'primary' : 'success'"
                  style="cursor: pointer; margin-left: 20px"
                  @click="handleUpdateStatus(scope.row)"
                >
                  {{ scope.row.isSel === 0 ? "待确认" : "已确认" }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination">
            <el-pagination
              background
              :current-page="homePageQuery.page"
              :page-size="homePageQuery.pageSize"
              layout="prev, pager, next"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>

      <!-- 左侧统计数据 -->
      <el-col :span="14">
        <el-card class="statistics-card">
          <!-- 上半部分统计数据 -->
          <el-row>
            <el-col :span="12">
              <!-- 合同总额 -->
              <div class="statistic-item">
                <div class="statistic-header">
                  <i class="el-icon-document" style="color: #409eff" />
                  <span>{{ year }}年合同总额</span>
                </div>
                <div class="statistic-main">
                  <span class="money-amount">{{
                    formatMoney(homeMessage.money)
                  }}</span>
                  <span class="money-unit">元</span>
                </div>
                <div class="statistic-footer">
                  合同总数：{{ homeMessage.count || 0 }}个
                </div>
              </div>

              <el-divider />

              <!-- 今日新增 -->
              <div class="statistic-item">
                <div class="statistic-header">
                  <i class="el-icon-date" style="color: #409eff" />
                  <span>今日新增</span>
                </div>
                <div class="statistic-main">
                  <span class="money-amount">{{
                    formatMoney(getTodayMoney)
                  }}</span>
                  <span class="money-unit">元</span>
                </div>
                <div class="statistic-footer">
                  新增合同：{{ getTodayCount || 0 }}个
                </div>
              </div>

              <el-divider />

              <!-- 昨日新增 -->
              <div class="statistic-item">
                <div class="statistic-header">
                  <i class="el-icon-time" style="color: #909399" />
                  <span>昨日新增</span>
                </div>
                <div class="statistic-main">
                  <span class="money-amount">{{
                    formatMoney(getYesterdayMoney)
                  }}</span>
                  <span class="money-unit">元</span>
                </div>
                <div class="statistic-footer">
                  新增合同：{{ getYesterdayCount || 0 }}个
                </div>
              </div>
            </el-col>

            <!-- 右侧饼图 -->
            <el-col :span="12">
              <!-- 合同总额 -->
              <!-- <div class="statistic-item">
                <div class="statistic-header">
                  <i class="el-icon-document" style="color: #409eff"></i>
                  <span>{{ year }}年合同总额</span>
                </div>
                <div class="statistic-main">
                  <span class="money-amount">{{
                    formatMoney(homeMessage.money)
                  }}</span>
                  <span class="money-unit">元</span>
                </div>
                <div class="statistic-footer">
                  合同总数：{{ homeMessage.count || 0 }}个
                </div>
              </div> -->
              <div class="chart-wrapper">
                <!-- <div class="statistic-item">
                <div class="statistic-header">
                  <i class="el-icon-document" style="color: #409eff"></i>
                  <span>{{ lastHomeMessage.year }}年合同总额</span>
                </div>
                <div class="statistic-main">
                  <span class="money-amount">{{
                    formatMoney(lastHomeMessage.money)
                  }}</span>
                  <span class="money-unit">元</span>
                </div>
                <div class="statistic-footer">
                  合同总数：{{ lastHomeMessage.count || 0 }}个
                  </div>
                </div> -->
                <div class="chart-container-box">
                  <h3 class="chart-title">{{ year }}年客户类型金额分布</h3>
                  <div ref="customerTypeChart" class="chart-container" />
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <el-card style="margin-top: 20px">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      <div v-else ref="logChart" style="height: 400px" />
    </el-card>
  </div>
</template>

<script>
import {
  selHomeMessageApi,
  selWaitMessageApi,
  updateWaitMessageByIdApi,
  selRealTimeMessageApi,
  selChartMessageApi
} from '@/api/dashboard'
import { selCustomerTypeMoneyListApi } from '@/api/data_board'
import { selUserAuditApi } from '@/api/login'
import * as echarts from 'echarts'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      loading: true,
      username: '周洪涛',
      currentYear: 2025,
      currentMonth: 3,
      admin: null,
      weekDays: [
        { label: '日', value: 'sun' },
        { label: '一', value: 'mon' },
        { label: '二', value: 'tue' },
        { label: '三', value: 'wed' },
        { label: '四', value: 'thu' },
        { label: '五', value: 'fri' },
        { label: '六', value: 'sat' }
      ],
      calendarData: [
        {
          sun: '23',
          mon: '24',
          tue: '25',
          wed: '26',
          thu: '27',
          fri: '28',
          sat: '1'
        },
        {
          sun: '2',
          mon: '3',
          tue: '4',
          wed: '5',
          thu: '6',
          fri: '7',
          sat: '8'
        },
        {
          sun: '9',
          mon: '10',
          tue: '11',
          wed: '12',
          thu: '13',
          fri: '14',
          sat: '15'
        },
        {
          sun: '16',
          mon: '17',
          tue: '18',
          wed: '19',
          thu: '20',
          fri: '21',
          sat: '22'
        },
        {
          sun: '23',
          mon: '24',
          tue: '25',
          wed: '26',
          thu: '27',
          fri: '28',
          sat: '29'
        },
        {
          sun: '30',
          mon: '31',
          tue: '1',
          wed: '2',
          thu: '3',
          fri: '4',
          sat: '5'
        }
      ],
      // 今年合同金额
      homeMessage: {
        money: 0,
        count: 0
      },
      // 去年合同金额
      lastHomeMessage: {
        money: 0,
        count: 0
      },
      count: null,
      realTimeMessage: [],
      todoItems: [], // 待办事项
      total: 0, // 待办事项总数
      value: new Date(), // 当前日期
      // id: "EE86F999-3FA3-4690-133C-08DD2E2339D1", // 当前用户id
      // id: "3844CEAE-B73C-424F-B333-08DC4166F79A",
      homePageQuery: {
        page: 1,
        pageSize: 10
      },
      startTime: 0,
      endTime: 0,
      dayRange: [],
      selChartMessage: [], // 金额数据
      customerTypeChart: null,
      year: '',
      logChart: null
    }
  },
  async created() {
    this.loading = true // 开始加载
    try {
      // 等待所有数据加载完成
      await this.fetchData()
      await this.selWaitMessage()
      await this.selUserAudit()

      // 设置默认的日期范围为当年
      this.year = new Date().getFullYear()
      const startDate = `${this.year}-01-01`
      const endDate = `${this.year}-12-31`

      // 设置默认日期范围
      this.dayRange = [startDate, endDate]
      this.startTime = new Date(this.dayRange[0]).getTime()
      this.endTime = new Date(this.dayRange[1] + ' 23:59:59').getTime()

      await this.selCustomerTypeMoneyList()
    } finally {
      this.loading = false // 结束加载状态
    }
  },

  methods: {
    // 是否修改密码
    async selUserAudit() {
      const res = await selUserAuditApi(this.userId)
      console.log(res)
      if (res.code === 1) {
        // this.userAudit = res.data;
      } else {
        this.$message.info('第一次登录需修改密码')
        await this.$store.dispatch('user/setNeedChangePassword', true)
        // 设置需要修改密码的状态
        this.$router.push({ name: '/Admin/ChangePassword/Index' })
      }
    },
    // 初始化客户类型饼图
    initCustomerTypeChart(data) {
      if (!this.$refs.customerTypeChart) return

      if (!this.customerTypeChart) {
        this.customerTypeChart = echarts.init(this.$refs.customerTypeChart)
      }

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c}元 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          top: 'middle'
        },
        series: [
          {
            name: '客户类型分布',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['65%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data.map((item) => ({
              name: item.name,
              value: item.money
            }))
          }
        ],
        color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de']
      }

      this.customerTypeChart.setOption(option)
    },
    // 待办事项点击
    handleTodoClick(row) {
      console.log(row)
      if (!this.admin) {
        this.$router.push({
          name: row.url,
          query: {
            no: row.projectNo
          }
        })
      } else {
        // this.$message.error("您没有权限访问该页面");
      }
    },
    // 处理窗口大小改变
    handleResize() {
      if (this.customerTypeChart) {
        this.customerTypeChart.resize()
      }
    },

    // 获取数据并初始化图表
    async selCustomerTypeMoneyList() {
      try {
        const res = await selCustomerTypeMoneyListApi({
          startTime: this.startTime,
          endTime: this.endTime
        })
        if (res.code === 1 && res.data) {
          this.initCustomerTypeChart(res.data)
        }
      } catch (error) {
        console.error('获取客户类型金额数据失败:', error)
      }
    },
    formatMoney(value) {
      if (!value) return '0.00'
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    },
    async fetchData() {
      try {
        const [homeRes, realTimeRes, increaseRes] = await Promise.all([
          selHomeMessageApi(this.userId),
          selRealTimeMessageApi(this.userId),
          selChartMessageApi(this.userId)
        ])
        if (homeRes.code === 1 && homeRes.data) {
          this.homeMessage = homeRes.data[1]
          this.year = homeRes.data[1].year
          this.lastHomeMessage = homeRes.data[0]
        }
        if (realTimeRes.code === 1 && realTimeRes.data) {
          this.realTimeMessage = realTimeRes.data
          // console.log(this.realTimeMessage);
        }
        if (increaseRes.code === 1 && increaseRes.data) {
          this.selChartMessage = increaseRes.data
          console.log('原始图表数据:', this.selChartMessage)
        }
      } catch (error) {
        console.error('获取数据失败:', error)
      }
    },
    // 待办事项
    async selWaitMessage() {
      try {
        const res = await selWaitMessageApi(this.homePageQuery, this.userId)
        this.todoItems = res.records || []
        this.total = res.total || 0
        this.admin = res.admin
        this.count = res.count
        this.$store.commit(
          'user/setIsAdministrators',
          res.admin === 1
        )
      } catch (error) {
        console.error('获取待办事项失败:', error)
        this.$message.error('获取待办事项失败')
      }
    },
    prevMonth() {
      // 切换到上个月
    },
    nextMonth() {
      // 切换到下个月
    },
    today() {
      // 回到今天
    },
    handleCurrentChange(val) {
      this.homePageQuery.page = val
      this.selWaitMessage()
    },
    async handleUpdateStatus(row) {
      try {
        const res = await updateWaitMessageByIdApi(row.id)
        if (res.code === 1) {
          this.$message.success('设置成功')
          // 更新本地数据状态
          // row.isSel = 1;
          // row.status = 2;
          this.selWaitMessage()
        } else {
          this.$message.error(res.msg || '更新失败')
        }
      } catch (error) {
        console.error('更新失败:', error)
        this.$message.error('更新失败')
      }
    },
    initLogChart() {
      if (!this.$refs.logChart) return

      const chart = echarts.init(this.$refs.logChart)

      // 获取数据
      const data2024 = this.selChartMessage[1] || []
      const data2025 = this.selChartMessage[0] || []

      // 定义重叠阈值
      const overlapThreshold = 200000 // 增加阈值，使更多接近的点被视为重叠

      const option = {
        title: {
          text: '合同金额同期对比',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{a} <br/>{b} : {c}',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          left: 'left'
        },
        xAxis: {
          type: 'category',
          name: '月份',
          splitLine: { show: false },
          data: [
            '1月',
            '2月',
            '3月',
            '4月',
            '5月',
            '6月',
            '7月',
            '8月',
            '9月',
            '10月',
            '11月',
            '12月'
          ]
        },
        grid: {
          left: '3%',
          right: '4%',
          top: '25%',
          bottom: '3%',
          containLabel: true
        },
        yAxis: {
          type: 'value',
          name: '金额',
          minorSplitLine: {
            show: true
          },
          interval: 500000
        },
        series: [
          {
            name: '2024年',
            type: 'line',
            data: data2024.map((value, index) => {
              const value2025 = data2025[index] || 0
              const isOverlap = Math.abs(value - value2025) < overlapThreshold

              return {
                value: value,
                label: {
                  show: true,
                  position: isOverlap
                    ? value < value2025
                      ? 'bottom'
                      : 'top'
                    : 'top',
                  formatter: '{c}',
                  color: '#5470c6',
                  distance: 5
                }
              }
            }),
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: '2025年',
            type: 'line',
            data: data2025.map((value, index) => {
              const value2024 = data2024[index] || 0
              const isOverlap = Math.abs(value - value2024) < overlapThreshold

              return {
                value: value,
                label: {
                  show: true,
                  position: isOverlap
                    ? value >= value2024
                      ? 'top'
                      : 'bottom'
                    : 'top',
                  formatter: '{c}',
                  color: '#91cc75',
                  distance: 5
                }
              }
            }),
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              color: '#91cc75'
            }
          }
        ]
      }

      chart.setOption(option)
      this.logChart = chart
    }
  },
  computed: {
    ...mapGetters(['userId', 'name']),
    // 今日新增
    getTodayMoney() {
      return this.realTimeMessage && this.realTimeMessage[1]
        ? this.realTimeMessage[1].money
        : 0
    },
    // 今日新增
    getTodayCount() {
      return this.realTimeMessage && this.realTimeMessage[1]
        ? this.realTimeMessage[1].count
        : 0
    },
    // 昨日新增
    getYesterdayMoney() {
      return this.realTimeMessage && this.realTimeMessage[0]
        ? this.realTimeMessage[0].money
        : 0
    },
    // 昨日新增
    getYesterdayCount() {
      return this.realTimeMessage && this.realTimeMessage[0]
        ? this.realTimeMessage[0].count
        : 0
    },
    // 计算待确认的数量
    pendingCount() {
      return this.todoItems.filter((item) => item.isSel === 0).length
    }
  },
  watch: {
    // 监听loading状态，当加载完成后初始化图表
    loading(newVal) {
      if (!newVal) {
        this.$nextTick(() => {
          // this.initCustomerTypeChart(this.customerTypeData || []);
          this.initLogChart()
        })
      }
    }
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.customerTypeChart) {
      this.customerTypeChart.dispose()
      this.customerTypeChart = null
    }
    if (this.logChart) {
      this.logChart.dispose()
      this.logChart = null
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.header-card {
  margin-bottom: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.main-content {
  display: flex;
  gap: 20px;
}

.calendar-section {
  flex: 3;
}

.todo-section {
  height: 100%;
  flex: 2;
}

/* .todo-badge {
  margin-top: 10px;
  margin-right: 40px;
} */

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.date-text {
  font-size: 16px;
  font-weight: bold;
}

.todo-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table {
  margin-top: 10px;
}

:deep(.el-card__body) {
  padding: 20px;
}

.el-tag {
  cursor: pointer;
}
.el-tag:hover {
  opacity: 0.8;
}

.statistics-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.statistics-group {
  display: flex;
  justify-content: space-around;
  gap: 20px;
}

.suffix-text {
  font-size: 14px;
  color: #606266;
  margin-left: 4px;
}

:deep(.el-statistic) {
  flex: 1;
}

:deep(.el-statistic__title) {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

:deep(.el-statistic__content) {
  font-size: 24px;
  color: #303133;
}

.statistics-card {
  padding: 24px;
  height: 100%;
  background: #fff;
}

.statistic-item {
  padding: 16px 0;
  transition: all 0.3s ease;
}

.statistic-item:hover {
  transform: translateY(-2px);
}

.statistic-item:hover .money-amount {
  color: #409eff;
}

.statistic-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}

.statistic-header i {
  font-size: 22px;
}

.statistic-header span {
  font-size: 16px;
  color: #333;
}

.statistic-main {
  margin: 16px 0;
}

.money-amount {
  font-size: 32px;
  font-weight: 500;
  color: #000;
  font-family: Arial, sans-serif;
  line-height: 1.1;
}

.money-unit {
  font-size: 14px;
  color: #999;
  margin-left: 4px;
}

.statistic-footer {
  font-size: 14px;
  color: #666;
  margin-top: 12px;
}

.el-divider {
  margin: 16px 0;
  background-color: #f0f0f0;
}

.chart-card {
  margin-top: 20px;
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.chart-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0 20px;

  .chart-container-box {
    .chart-title {
      font-size: 22px;
      font-weight: bold;
      color: #303133;
      margin: 0;
      padding: 20px 0;
      text-align: center;
    }

    .chart-container {
      width: 100%;
      height: 320px;
      margin-top: 20px;
    }
  }
}

.loading-container {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
